package com.tpshion.cloud.core.autoconfig;

import com.tpshion.cloud.core.autoconfig.properties.MinioClientProperties;
import com.tpshion.cloud.core.autoconfig.support.MinioTemplate;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * minioClient自动配置类（对象存储客户端）
 */
@Configuration
@ConditionalOnClass(MinioClient.class)
@EnableConfigurationProperties(MinioClientProperties.class)
@ConditionalOnProperty(value = "oss.minio.enabled")
public class MinioClientAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MinioClientAutoConfiguration.class);

    private MinioClientProperties properties;

    public MinioClientAutoConfiguration(MinioClientProperties properties){
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
        log.info("init miniClient. endpoint:{} accesskey:{} secretkey:{}",
                properties.getEndpoint(),properties.getAccesskey(),properties.getSecretkey());

        return new MinioClient(properties.getEndpoint(),properties.getAccesskey(),properties.getSecretkey());
    }

    @Bean
    @ConditionalOnBean(MinioClient.class)
    public MinioTemplate minioTemplate(MinioClient minioClient){
        log.info("init minioTemplate. minioClient:{}",minioClient);
        return new MinioTemplate(minioClient,properties);
    }
}
